<template>
  <el-row>
    <el-col :span="8" class="el-col">
      <label>机柜：</label>
    </el-col>
    <el-col :span="16">
      <el-autocomplete
        class="el-autocomplete"
        size="small"
        @select="handleSelect"
        v-model="rackName"
        :fetch-suggestions="querySearch"
      ></el-autocomplete>
    </el-col>
  </el-row>
</template>

<script>
import { getRackListByModule } from '../../api/itopApi'
export default {
  name: 'MySelectRack',
  props: {
    moduleId: {
      required: true
    }
  },
  watch: {
    moduleId(newId, oldId) {
      if (!newId) {
        this.rackName = ''
        this.moduleList = []
      } else {
        this.moduleName = ''
        this.loadRackList(newId)
      }
    }
  },
  data() {
    return {
      rackList: [],
      rackName: ''
    }
  },
  methods: {
    querySearch(queryString, cb) {
      if (queryString) {
        cb(this.rackList.filter(this.createFilter(queryString)))
      } else {
        cb(this.rackList)
      }
      let results = queryString
        ? this.rackList.filter(this.createFilter(queryString))
        : this.rackList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return rack => {
        return rack.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    loadRackList(moduleId) {
      const self = this
      getRackListByModule(moduleId).then(data => {
        self.rackList = data
        self.rackList.forEach(item => {
          item.value = item.name
        })
      })
    },
    handleSelect(item) {
      this.$emit('select', item)
    },
    reset() {
      this.rackName = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.el-autocomplete {
  width: 100%;
}
</style>
